package com.course.redisson.service.RMap;

import com.course.common.enums.Constant;
import com.course.model.mapper.redisson.UserOrderMapper;
import org.redisson.api.RMapCache;
import org.redisson.api.RedissonClient;
import org.redisson.api.map.event.EntryEvent;
import org.redisson.api.map.event.EntryExpiredListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @PROJECT_NAME: course
 * @DESCRIPTION:
 * @Author: 涂玄武
 * @DATE: 2021/6/7 10:11
 */
@Service
public class RMapCacheService implements ApplicationRunner, Ordered {

    private static final Logger logger = LoggerFactory.getLogger(RMapCacheService.class);

    @Resource
    private RedissonClient redissonClient;

    @Resource
    private UserOrderMapper userOrderMapper;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        logger.info("--在项目一直跑的过程中，不间断地执行一些我们自定义的服务逻辑 --");

        this.listenExpireUserOrder();
    }

    /**
     * 监听并失效迟迟未支付的用户订单
     */
    private void listenExpireUserOrder() {
        try {
            RMapCache<Object, Object> rMapCache = redissonClient.getMapCache(Constant.RedisMapCacheUserOrder);
            rMapCache.addListener((EntryExpiredListener<Integer, String>) event -> {

                logger.info("---失效监听用户过期的订单,监听到消息：key={},订单编号={}", event.getKey(), event.getValue());

                userOrderMapper.updateExpireOrder(event.getValue(), Constant.OrderPayStatus.UnPay.getCode(), Constant.OrderPayStatus.SystemCancel.getCode());
            });

        } catch (Exception e) {
            logger.error("Redisson-失效监听用户过期的订单-发生异常：", e.fillInStackTrace());
        }
    }

    @Override
    public int getOrder() {
        return 2;
    }
}
